package org.alicuu.dao;

import org.alicuu.toolkit.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Danny
 * Date: 16/07/10
 * Time: 23:06
 */
public class JavaFileUtil {
    /**
     * Generate java property info from field info.
     */
    public static JavaFieldGetSet createFieldGetSetSrc(ColumnInfo column, TypeConvertor convertor) {
        JavaFieldGetSet fieldGetSet = new JavaFieldGetSet();
        String javaFieldType = convertor.databaseTypeToJavaType(column.getDataType());
        fieldGetSet.setFieldInfo("\tprivate " + javaFieldType + " " + column.getColName() + ";\n");

        StringBuffer getSrc = new StringBuffer();
        // 生成get方法源码
        getSrc.append("\tpublic " + javaFieldType + " get" + StringUtil.firstCharUpperCase(column.getColName()) + "(){\n");
        getSrc.append("\t\treturn " + column.getColName() + ";\n");
        getSrc.append("\t}\n");
        fieldGetSet.setGetInfo(getSrc.toString());

        //生成set方法源码
        StringBuffer setSrc = new StringBuffer();
        setSrc.append("\tpublic void set" + StringUtil.firstCharUpperCase(column.getColName()) + "(");
        setSrc.append(javaFieldType + " " + column.getColName() + "){\n");
        setSrc.append("\t\tthis." + column.getColName() + "=" + column.getColName() + ";\n");
        setSrc.append("\t}\n");
        fieldGetSet.setSetInfo(setSrc.toString());

        return fieldGetSet;
    }

    /**
     * Generate java source code from table info.
     */
    public static String createJavaSrc(TableInfo tableInfo, TypeConvertor convertor) {
        StringBuffer src = new StringBuffer();
        Map<String, ColumnInfo> columns = tableInfo.getColumns();
        List<JavaFieldGetSet> javaFields = new ArrayList<>();
        for (ColumnInfo c : columns.values())
            javaFields.add(createFieldGetSetSrc(c, convertor));
        // package
        src.append("package " + DBManager.getConf().getPersistentObjPackage() + ";\n\n");

        // import
        src.append("import java.sql.*;\n");
        src.append("import java.util.*;\n\n");
        // class declaration
        src.append("public class " + StringUtil.firstCharUpperCase(tableInfo.getTableName() + " {\n\n"));

        for (JavaFieldGetSet f : javaFields)
            src.append(f.getFieldInfo());

        src.append("\n\n");

        // getter
        for (JavaFieldGetSet f : javaFields)
            src.append(f.getGetInfo());

        // setter
        for (JavaFieldGetSet f : javaFields)
            src.append(f.getSetInfo());
        src.append("}\n");

        return src.toString();
    }


}
